package com.smart.community.commons.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.smart.community.commons.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 响应格式配置类
 * 功能说明：
 * 1. 统一API响应格式
 * 2. 确保返回标准JSON格式
 * 3. 添加数据格式验证
 * 4. 防止类型信息泄露
 * 
 * @author Wu.Liang
 * @version 1.0.0
 * @since 2024-12-21
 */
@Slf4j
@Configuration
@RestControllerAdvice
public class ResponseFormatConfig implements ResponseBodyAdvice<Object> {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    @Qualifier("customModule")
    private SimpleModule customModule;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 只处理返回Result类型的接口
        return returnType.getParameterType().equals(Result.class) || 
               returnType.getParameterType().equals(Object.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                ServerHttpRequest request, ServerHttpResponse response) {
        try {
            if (body instanceof Result) {
                // 如果已经是Result类型，直接返回
                Result<?> result = (Result<?>) body;
                if (result.getData() != null) {
                    validateDataFormat(result.getData());
                }
                return result;
            } else {
                // 如果不是Result类型，包装成Result
                Result<Object> result = Result.success(body);
                if (result.getData() != null) {
                    validateDataFormat(result.getData());
                }
                return result;
            }
        } catch (Exception e) {
            log.error("响应格式处理失败: {}", e.getMessage());
            return Result.fail("响应格式处理失败");
        }
    }

    /**
     * 验证数据格式
     */
    private void validateDataFormat(Object data) {
        try {
            // 将数据转换为JSON字符串，检查是否包含类型信息
            String jsonString = objectMapper.writeValueAsString(data);
            
            // 检查JSON格式是否正确
            if (!isValidJson(jsonString)) {
                log.error("响应数据JSON格式不正确: {}", jsonString);
                return;
            }
            
            // 检查是否包含Java类型信息
            if (jsonString.contains("java.") || jsonString.contains("com.")) {
                log.warn("检测到响应数据包含类型信息，数据: {}", jsonString);
                // 在实际生产环境中，可以考虑抛出异常或进行数据清理
            }
        } catch (Exception e) {
            log.error("数据格式验证失败: {}", e.getMessage());
        }
    }

    /**
     * 检查JSON格式是否正确
     */
    private boolean isValidJson(String jsonString) {
        try {
            objectMapper.readTree(jsonString);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
